package com.dd.cloud.user.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dd.cloud.user.DTO.yf.ReturnCheckDrugKlStockResultDTO;
import com.dd.cloud.user.DTO.yf.SendCheckDrugKlExcessDTO;
import com.dd.cloud.user.DTO.yf.SendCheckDrugKlStockDTO;
import com.dd.cloud.user.entity.order.OrderPay;
import com.dd.cloud.user.entity.phar.AuxiliaryMaterialSetting;
import com.dd.cloud.user.entity.phar.AuxiliaryMaterialSettingRecord;
import com.dd.cloud.user.entity.phar.PharExpressRule;
import com.dd.cloud.user.entity.phar.PharSetFeeRecord;
import com.dd.cloud.user.req.phar.*;
import com.dd.cloud.user.res.admin.AdminUserDetailRes;
import com.dd.cloud.user.res.phar.*;
import com.dd.cloud.user.service.order.IOrderPayService;
import com.dd.cloud.user.service.phar.IPharmacyChooseService;
import com.dd.cloud.user.service.phar.IPharmacyService;
import com.dd.cloud.user.service.phar.IPharmacyUserService;
import com.dd.cloud.user.service.phar.pharservice.*;
import com.dd.cloud.user.service.pres.IAuxiliaryMaterialSettingService;
import com.dd.cloud.user.service.pres.IDrugsModelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 药房控制器
 *
 * @author Lx
 * @version 1.0
 */
@RestController
@RequestMapping("/pharmacy")
@Validated
@Slf4j
public class PharmacyController {
    @Autowired
    private IPharmacyChooseService pharmacyChooseService;
    @Autowired
    private IPharmacyUserService pharmacyUserService;
    @Autowired
    private IPharmacyService pharmacyService;
    @Autowired
    private IAuxiliaryMaterialSettingService auxiliaryMaterialSettingService;
    @Autowired
    private YfPharService yfPharService;
    @Autowired
    private IDrugsModelService drugsModelService;

    @Autowired
    private HrPharService hrPharService;

    @Autowired
    private IOrderPayService orderPayService;
    @Autowired
    private HstPharService hstPharService;
    @Autowired
    private PharServiceBeanInterface pharServiceBeanInterface;

    /**
     * 获取机构默认使用的药房
     *
     * @param mechanId
     * @return
     */
    @GetMapping("/by/mechan")
    public ResponseEntity<PharmacyChooseRes> getPharmacy(Integer mechanId) {
        PharmacyChooseRes res = pharmacyChooseService.getPharChooseByMechan(mechanId);
        return ResponseEntity.ok(res);
    }

    /**
     * 获取机构的药房列表 默认使用药房
     *
     * @return
     */
    @GetMapping("/list/by/mechan")
    public ResponseEntity<List<PharmacyChooseRes>> getPharChooseListByMechan(Integer mechanId) {
        List<PharmacyChooseRes> res = pharmacyChooseService.getPharChooseListByMechan(mechanId);
        return ResponseEntity.ok(res);
    }

    /**
     * 查询药房管理员列表
     *
     * @param req
     * @return
     */
    @GetMapping("/user/page")
    public ResponseEntity<Page<StroeUserPageRes>> getStoreUserPage(@Valid StoreUserPageReq req) {
        Page<StroeUserPageRes> storeUserPage = pharmacyUserService.getStoreUserPage(req);
        return ResponseEntity.ok(storeUserPage);
    }

    /**
     * 修改药房管理员
     *
     * @param req
     * @return
     */
    @PostMapping("/user/update")
    public ResponseEntity<Void> updateStoreUser(@Valid @RequestBody StoreUserUpdateReq req) {
        pharmacyUserService.updateStoreUser(req);
        return ResponseEntity.ok().build();
    }

    /**
     * 添加药房管理员
     *
     * @param req
     * @return
     */
    @PostMapping("/user/add")
    public ResponseEntity<Void> addStoreUser(@Valid @RequestBody StoreUserAddReq req) {
        pharmacyUserService.addStoreUser(req);
        return ResponseEntity.ok().build();
    }

    /**
     * 查询药房管理员详情
     */
    @GetMapping("/user/detail")
    public ResponseEntity<AdminUserDetailRes> getUserPage(@NotNull(message = "管理员id不能为空") Integer id) {
        AdminUserDetailRes res = pharmacyUserService.getAdminUserDetail(id);
        return ResponseEntity.ok(res);
    }

    /**
     * 修改药房管理员状态
     *
     * @param id
     * @return
     */
    @PostMapping("/user/update/status")
    public ResponseEntity<Void> updateStoreUserStatus(@NotNull(message = "管理员id不能为空") Integer id, @NotNull(message = "状态不能为空") Integer status) {
        pharmacyUserService.updateStoreUserStatus(id, status);
        return ResponseEntity.ok().build();
    }

    /**
     *登录
     */
    /**
     * 门店管理员用户登录 密码
     *
     * @param request
     * @param response
     * @param account
     * @param password
     * @return
     */
    @PostMapping("/user/login/pwd")
    public ResponseEntity<StoreUserLoginRes> storeUserLoginPwd(HttpServletRequest request, HttpServletResponse response, @NotBlank(message = "账号不能为空") String account, @NotBlank(message = "密码不能为空") String password) {
        StoreUserLoginRes storeUserLoginRes = pharmacyUserService.storeUserLoginPwd(request, response, account, password);
        return ResponseEntity.ok(storeUserLoginRes);
    }

    /**
     * 药房管理员用户修改密码
     *
     * @param oldPwd
     * @param newPwd1
     * @param newPwd2
     */
    @PostMapping("/user/update/pwd")
    public ResponseEntity<Void> updateStoreUserPwd(@NotBlank(message = "原密码不能为空") String oldPwd, @NotBlank(message = "新密码不能为空") String newPwd1, @NotBlank(message = "重复密码不能为空") String newPwd2) {
        pharmacyUserService.updateStoreUserPwd(oldPwd, newPwd1, newPwd2);
        return ResponseEntity.ok().build();
    }


    /**
     * 门店管理员用户找回密码
     *
     * @param phone
     * @param code
     * @param pwd1
     * @param pwd2
     */
    @PostMapping("/user/find/pwd")
    public ResponseEntity<Void> findStoreUserPwd(@NotBlank(message = "手机号不能为空") String phone, @NotBlank(message = "验证码不能为空") String code, @NotBlank(message = "新密码不能为空") String pwd1, @NotBlank(message = "重复密码不能为空") String pwd2) {
        pharmacyUserService.findStoreUserPwd(phone, code, pwd1, pwd2);
        return ResponseEntity.ok().build();
    }


    /**
     * 退出登录
     */
    @PostMapping("/loginOut")
    public ResponseEntity<Void> loginOut(HttpServletRequest request, HttpServletResponse response) {
        pharmacyUserService.loginOut(request, response);
        return ResponseEntity.ok().build();
    }

    /**
     * 药房管理员登录 验证码
     *
     * @param request
     * @param response
     * @param phone
     * @param code
     * @return
     */
    @PostMapping("/user/login/code")
    public ResponseEntity<StoreUserLoginRes> merchantUserLoginCode(HttpServletRequest request, HttpServletResponse response, @NotBlank(message = "手机号不能为空") String phone, @NotBlank(message = "验证码不能为空") String code) {
        StoreUserLoginRes res = pharmacyUserService.pharmacyUserLoginCode(request, response, phone, code);
        return ResponseEntity.ok(res);
    }

    /**
     * 查看运费用详情
     */
    @GetMapping("/set/expFee/detail")
    public ResponseEntity<PharExpressRule> getPharmacyExpFee() {
        PharExpressRule res = pharmacyUserService.getPharmacyExpFee();
        return ResponseEntity.ok(res);
    }

    /**
     * 查看代煎费
     */
    @GetMapping("/set/fryFee/detail")
    public ResponseEntity<PharmacyProcessTypeRes> getPharmacyFryFee() {
        PharmacyProcessTypeRes res = pharmacyUserService.getPharmacyFryFee();
        return ResponseEntity.ok(res);
    }

    /**
     * 查询代煎费列表
     */
    @GetMapping("/set/fryFee/list")
    public ResponseEntity<PharmacyProcessTypeRes> getFryingFeePage() {
        PharmacyProcessTypeRes res = pharmacyUserService.getFryingFeePage();
        return ResponseEntity.ok(res);
    }


    /**
     * 修改物流设置费
     */
    @PostMapping("/set/expFee")
    public ResponseEntity<Void> updatePharmacyExpFee(@Valid @RequestBody PharExpRuleRes pharExpRuleRes) {
        pharmacyUserService.updatePharmacyExpFee(pharExpRuleRes);
        return ResponseEntity.ok().build();
    }

    /**
     * 修改代煎费
     */
    @PostMapping("/set/fryFee")
    public ResponseEntity<Void> updatePharmacyFryFee(@Valid @RequestBody PharFryRuleReq pharFryRuleReq) {
        pharmacyUserService.updatePharmacyFryFee(pharFryRuleReq);
        return ResponseEntity.ok().build();
    }


    /**
     * 查询修改记录
     */
    @GetMapping("/set/fee/page")
    public ResponseEntity<Page<PharSetFeeRecord>> getSetFeePage(@Valid PharSetReq pharSetReq) {
        Page<PharSetFeeRecord> storeUserPage = pharmacyUserService.getSetFeePage(pharSetReq);
        return ResponseEntity.ok(storeUserPage);
    }

    /**
     * 统计药房首页头部数据
     *
     * @return
     */
    @GetMapping("/home/top/statistics")
    public ResponseEntity<PharmacyHomeTopStatisticsRes> statisticsPharmacyHomeTop() {
        PharmacyHomeTopStatisticsRes res = pharmacyService.statisticsPharmacyHomeTop();
        return ResponseEntity.ok(res);
    }

    /**
     * 统计药房首页近期收入情况数据
     *
     * @param req
     * @return
     */
    @GetMapping("/home/chart/statistics")
    public ResponseEntity<PharmacyHomeChartStatisticsRes> statisticsPharmacyHomeChart(PharmacyHomeChartStatisticsReq req) {
        PharmacyHomeChartStatisticsRes res = pharmacyService.statisticsPharmacyHomeChart(req);
        return ResponseEntity.ok(res);
    }

    /**
     * 统计药房首页药品总用量排行榜
     *
     * @return
     */
    @GetMapping("/home/drug/dosage/statistics")
    public ResponseEntity<IPage<PharmacyHomeDrugDosageStatisticsRes>> statisticsPharmacyHomeDrugDosage(PharmacyHomeDrugDosageStatisticsReq req) {
        IPage<PharmacyHomeDrugDosageStatisticsRes> res = pharmacyService.statisticsPharmacyHomeDrugDosage(req);
        return ResponseEntity.ok(res);
    }


    /**
     * 查询药房可查询的机构 下拉框使用
     *
     * @return
     */
    @GetMapping("/mechan/select/list")
    public ResponseEntity<List<PharmacyMechanSelectRes>> queryPharmacyMechanSelect() {
        List<PharmacyMechanSelectRes> res = pharmacyService.queryPharmacyMechanSelect();
        return ResponseEntity.ok(res);
    }


    /**
     * 查询药房开始收入时间
     *
     * @return
     */
    @GetMapping("/first/income/date")
    public ResponseEntity<LocalDateTime> queryFirstPharmacyIncomeDate() {
        LocalDateTime res = pharmacyService.queryFirstPharmacyIncomeDate();
        return ResponseEntity.ok(res);
    }

    /**
     * 查询药房代煎与物流费
     */
    @GetMapping("/fee")
    public ResponseEntity<PharFeeRes> queryFee(@RequestParam("pharId") Integer pharId) {
        PharFeeRes pharFeeRes = pharmacyUserService.queryFee(pharId);
        return ResponseEntity.ok(pharFeeRes);
    }

    /**
     * 查询药房列表 select框查询
     *
     * @param ids 药房id 数组, 选全部传空
     * @return
     */
    @GetMapping("/list")
    public ResponseEntity<List<PharListRes>> getPharPage(Integer[] ids) {
        List<PharListRes> res = pharmacyService.getPharmacyList(ids);
        return ResponseEntity.ok(res);
    }

    /**
     * 查询药房列表
     *
     * @return
     */
    @GetMapping("/page")
    public ResponseEntity<IPage<PharmacyPageRes>> getPharPage(@Valid PharmacyPageReq req) {
        Page<PharmacyPageRes> res = pharmacyService.getPharmacyPage(req);
        return ResponseEntity.ok(res);
    }

    /**
     * 添加药房
     *
     * @return
     */
    @PostMapping("/add")
    public ResponseEntity<Void> addPhar(@Valid @RequestBody AddPharmacyReq req) {
        pharmacyService.addPharmacy(req);
        return ResponseEntity.ok().build();
    }

    /**
     * 修改药房
     *
     * @return
     */
    @PostMapping("/update")
    public ResponseEntity<Void> updatePhar(@Valid @RequestBody UpdatePharmacyReq req) {
        pharmacyService.updatePharmacy(req);
        return ResponseEntity.ok().build();
    }

    /**
     * 修改药房状态
     *
     * @return
     */
    @PostMapping("/update/status")
    public ResponseEntity<Void> updatePharStatus(@NotNull(message = "id不能为空") Integer id, @NotNull(message = "状态不能为空") Integer status) {
        pharmacyService.updatePharmacyStatus(id, status);
        return ResponseEntity.ok().build();
    }

    /**
     * 查询辅料列表
     */
    @GetMapping("/auxiliary/material/setting/page")
    public ResponseEntity<IPage<AuxiliaryMaterialSetting>> getAuxiliaryMaterialSettingPage(@Valid AuxiliarySettingReq req) {
        Page<AuxiliaryMaterialSetting> res = auxiliaryMaterialSettingService.getAuxiliaryMaterialSettingPage(req);
        return ResponseEntity.ok(res);
    }

    /**
     * 查看辅料设置详情
     */
    @GetMapping("/auxiliary/material/setting/detail")
    public ResponseEntity<AuxiliaryMaterialSetting> getAuxiliaryDetail(@RequestParam("id") Integer id) {
        AuxiliaryMaterialSetting res = auxiliaryMaterialSettingService.getAuxiliaryDetail(id);
        return ResponseEntity.ok(res);
    }

    /**
     * 修改辅料设置状态
     */
    @PostMapping("/auxiliary/material/setting/status")
    public ResponseEntity<Void> updateAuxiliaryStatus(@NotNull(message = "id不能为空") Integer id, @NotNull(message = "状态不能为空") Integer status) {
        auxiliaryMaterialSettingService.updateAuxiliaryStatus(id, status);
        return ResponseEntity.ok().build();
    }

    /**
     * 添加辅料设置
     */
    @PostMapping("/auxiliary/material/setting")
    public ResponseEntity<Void> addAuxiliarySetting(@Valid @RequestBody AddAuxiliarySettingReq addAuxiliarySettingReq) {
        auxiliaryMaterialSettingService.addAuxiliarySetting(addAuxiliarySettingReq);
        return ResponseEntity.ok().build();
    }

    /**
     * 编辑辅料设置
     */
    @PostMapping("/auxiliary/material/setting/update")
    public ResponseEntity<Void> updateAuxiliarySetting(@Valid @RequestBody UpdateAuxiliarySettingReq updateAuxiliarySettingReq) {
        auxiliaryMaterialSettingService.updateAuxiliarySetting(updateAuxiliarySettingReq);
        return ResponseEntity.ok().build();
    }

    /**
     * 通过辅料名称等值查询
     */
    @GetMapping("/auxiliary/material/setting/query")
    public ResponseEntity<AuxiliaryMaterialSetting> queryFeePrice(@RequestParam(value = "pharId") Integer pharId) {
        AuxiliaryMaterialSetting auxiliaryMaterialSetting = auxiliaryMaterialSettingService.queryFeePrice(pharId);
        return ResponseEntity.ok(auxiliaryMaterialSetting);
    }

    /**
     * 获取修改记录
     */
    @GetMapping("/auxiliary/material/setting/record/page")
    public ResponseEntity<IPage<AuxiliaryMaterialSettingRecord>> getRecord(AuxiliarySettingRecordReq auxiliarySettingReq) {
        IPage<AuxiliaryMaterialSettingRecord> res = auxiliaryMaterialSettingService.getRecord(auxiliarySettingReq);
        return ResponseEntity.ok(res);
    }

    /**
     * 查询饮片加工费
     */
    @GetMapping("/rule/one/list")
    public ResponseEntity<List<PharOneRuleFeeRes>> getOneRuleList(@RequestParam(value = "types") String types, @RequestParam(value = "pharId", required = false) Integer pharId) {
        List<PharOneRuleFeeRes> res = pharmacyUserService.getOneRuleList(types, pharId);
        return ResponseEntity.ok(res);
    }

    /**
     * 查询其他加工费
     */
    @GetMapping("/rule/two/list")
    public ResponseEntity<List<PharTwoRuleFeeRes>> getTwoRuleList(@RequestParam(value = "types") String types, @RequestParam(value = "pharId", required = false) Integer pharId) {
        List<PharTwoRuleFeeRes> res = pharmacyUserService.getTwoRuleList(types, pharId);
        return ResponseEntity.ok(res);
    }

    /**
     * 根据药房id查询查看运费用详情
     */
    @GetMapping("/set/rule/detail")
    public ResponseEntity<PharRuleRes> getPharmacyRuleRes(@RequestParam("pharId") Integer pharId) {
        PharRuleRes res = pharmacyUserService.getPharmacyRuleRes(pharId);
        return ResponseEntity.ok(res);
    }

    /**
     * 拉取一方制药颗粒药材数据
     *
     * @return
     */
    @PostMapping("/pull/yf/kl/drug")
    public ResponseEntity<Void> pullYfKlDrug() {
        yfPharService.syncYfKlDrug();
        return ResponseEntity.ok().build();
    }

    /**
     * 检查一方制药颗粒药材库存
     *
     * @return
     */
    @PostMapping("/check/yf/kl/drug/stock")
    public ResponseEntity<ReturnCheckDrugKlStockResultDTO> checkDrugKlStock(@RequestBody String body) {
        log.info("body:{}", body);
        SendCheckDrugKlStockDTO send = JSON.parseObject(body, SendCheckDrugKlStockDTO.class);
        log.info("send:{}", send);
        ReturnCheckDrugKlStockResultDTO res = yfPharService.checkDrugKlStock(send);
        return ResponseEntity.ok(res);
    }

    /**
     * 检查一方制药颗粒药材超量/配伍禁忌
     *
     * @return
     */
    @PostMapping("/check/yf/kl/drug/excess")
    public ResponseEntity<Map<?, ?>> checkDrugKlExcess(@Valid SendCheckDrugKlExcessDTO send) {
        Map<?, ?> res = yfPharService.checkDrugKlExcess(send);
        return ResponseEntity.ok(res);
    }

    /**
     * 手动处理一方制药状态流转
     */
    @PostMapping("/hand/yf/status/roam")
    public ResponseEntity<Void> presStatusRoamYf() {
        yfPharService.presStatusRoamYf();
        return ResponseEntity.ok().build();
    }

    /**
     * 导入一方制药颗粒药材价格
     *
     * @param file
     */
    @PostMapping("/import/yf/kl/price")
    public ResponseEntity<Void> importYfKlDrugPrice(MultipartFile file) {
        drugsModelService.importYfKlDrugPrice(file);
        return ResponseEntity.ok().build();
    }

    /**
     * 拉取三九制药药材(先保存饮片相关的药品)
     */
    @PostMapping("/pull/hr/drug")
    public ResponseEntity<Void> pullHrDrug() {
        hrPharService.pullHrDrug();
        return ResponseEntity.ok().build();
    }

    /**
     * 导入华润制药药品价格
     */
    @PostMapping("/import/hr/price")
    public ResponseEntity<Void> importHrDrugPrice(MultipartFile file) {
        drugsModelService.importHrDrugPrice(file);
        return ResponseEntity.ok().build();
    }

    /**
     * 手动发送处方(测试使用)
     */
    @PostMapping("/send/hr/pres")
    ResponseEntity<Void> sendPres(String orderNo) {
        OrderPay orderPay = orderPayService.getOrderPay(orderNo);
        hrPharService.sendPresToPhar(orderPay);
        return ResponseEntity.ok().build();
    }

    /**
     * 手动和顺堂发送处方(测试使用)
     */
    @PostMapping("/send/hst/pres")
    ResponseEntity<Void> sendHstPres(String orderNo) {
        OrderPay orderPay = orderPayService.getOrderPay(orderNo);
        PharServiceInterface pharServiceInterface = pharServiceBeanInterface.getPharService(orderPay);
        pharServiceInterface.sendPresToPhar(orderPay);
        return ResponseEntity.ok().build();
    }

    /**
     * 手动和顺堂发送处方(测试使用)
     */
    @PostMapping("/query/hst/pres")
    ResponseEntity<Void> queryHstPres() {
        hstPharService.presStatusRoamHst();
        return ResponseEntity.ok().build();
    }

    /**
     * 拉取和顺堂药材(先保存饮片相关的药品)
     */
    @PostMapping("/pull/hst/drug")
    public ResponseEntity<Void> pullHstDrug() {
        hstPharService.pullHstDrug();
        return ResponseEntity.ok().build();
    }

    /**
     * 设置物流回调地址
     */
    @PostMapping("/set/hst/express/url")
    public ResponseEntity<Void> setExpressUrl() {
        hstPharService.setExpressUrl();
        return ResponseEntity.ok().build();
    }

    /**
     * 手动上传附件
     */
    @PostMapping("/hr/upload")
    ResponseEntity<Void> upload(String orderNo) {
        hrPharService.upload(orderNo);
        return ResponseEntity.ok().build();
    }
}
